﻿using System;
using System.Web.Mvc;
using System.ServiceModel.Syndication;
using ConferenceZoom.DTDBService;
using System.Linq;
using System.Xml;
using System.Text;

namespace ConferenceZoom.Actions
{
    /// <summary>
    /// An action result that converts a list of conferences into an RSS feed.
    /// </summary>
    public class RssActionResult : ActionResult
    {

        public BasicTalkInfo[] Talks { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public Uri FeedLink { get; set; }

        /// <summary>
        /// URL used for the base to reference a talk.
        /// </summary>
        public string BaseURL { get; set; }

        /// <summary>
        /// Set some defaults up!
        /// </summary>
        public RssActionResult()
        {
            BaseURL = "http://deeptalk.phys.washington.edu/Conference/Conference/Show";
        }

        /// <summary>
        /// Return the RSS for the info of what is going on.
        /// </summary>
        /// <param name="context"></param>
        public override void ExecuteResult(ControllerContext context)
        {
            ///
            /// Convert the talks to feeds
            /// 

            var items = from t in Talks
                        select ConvertToFeedItem(t);

            ///
            /// Render the RSS feed now
            /// 

            context.HttpContext.Response.ContentType = "application/rss+xml";

            SyndicationFeed feed = new SyndicationFeed(Title, Description, FeedLink, items);
            Rss20FeedFormatter rss = new Rss20FeedFormatter(feed);
            using (XmlWriter wr = XmlWriter.Create(context.HttpContext.Response.Output))
            {
                rss.WriteTo(wr);
            }
        }

        /// <summary>
        /// Takes a single talk and converts it to a RSS item... simple, mate! :-)
        /// </summary>
        /// <param name="talk"></param>
        /// <returns></returns>
        private SyndicationItem ConvertToFeedItem(BasicTalkInfo talk)
        {
            StringBuilder contentText = new StringBuilder();
            contentText.Append(talk.Title);
            contentText.Append(" - started on ");
            contentText.Append(talk.StartDate);

            Uri uri = new Uri(BaseURL + "/" + talk.ID.ToString(), UriKind.Relative);

            SyndicationItem item = new SyndicationItem(talk.Title, contentText.ToString(), uri);
            item.Id = talk.ID.ToString();

            return item;
        }
    }
}
